package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    /*@RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        try {
            Employee employee = employeeService.login(username, password);
            //session.setAttribute("EMPLOYEE_IN_SESSION",employee);
            UserContext.setCurrentUser(employee);
            //判断是不是超管
            if (!employee.isAdmin()) {
                List<String> permissions = permissionService.selectByEmployeeId(employee.getId());
                //session.setAttribute("EXPRESSION_IN_SESSION",permissions);
                UserContext.setExpression(permissions);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "用户名或密码错误");
        }
    }*/

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        try {
            //封装令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //利用api来进行登录
            SecurityUtils.getSubject().login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        } catch (DisabledAccountException e) {
            return new JsonResult(false, "账号被禁用");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }
    }

    /*@RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }*/
}
